package com.superhelper.app.service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.superhelper.app.common.Consts;
import com.superhelper.app.domain.DeliverRecordOrder;
import com.superhelper.app.domain.Order;
import com.superhelper.app.domain.Resp;
import com.superhelper.app.mapper.AdminMapper;
import com.superhelper.app.mapper.DeliverMapper;
import com.superhelper.app.service.deliver.IDeliverService;
import com.superhelper.common.domain.AuserDeliver;
import com.superhelper.common.domain.AuserShop;
import com.superhelper.common.domain.DadaReasons;
import com.superhelper.common.domain.DeliverAccount;
import com.superhelper.common.domain.DeliverRecord;
import com.superhelper.common.domain.DeliverRecordStatus;
import com.superhelper.common.domain.WifiAccount;
import com.superhelper.common.service.FeiEService;

@Service
public class DeliverService {
    protected Logger log = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private DeliverMapper deliverMapper;
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private OrderService orderService;
    @Autowired
    private IDeliverService dataService;
    @Autowired
    private FeiEService feiEService;

    public int addSet(AuserDeliver entity) {
	return deliverMapper.addAuserDeviler(entity);
    }

    public int updateDeliverSwitch(Long auserId, Integer state) {
	return deliverMapper.updateDeliverSwitch(auserId, state);
    }

    public AuserDeliver getAuserDeliver(Long auserId) {
	return deliverMapper.getAuserDeliver(auserId);
    }

    public Resp getDeliverRecordList(Long auserId, Long timestamp, Integer pageSize, Integer status) {
	List<DeliverRecordOrder> result = new ArrayList<DeliverRecordOrder>();
	List<AuserShop> shops = adminMapper.getAuserShopsByAuserId(auserId);
	List<Long> shopIds = new ArrayList<Long>();
	for (AuserShop a : shops) {
	    shopIds.add(a.getId());
	}
	if (!shops.isEmpty()) {
	    if (timestamp == 0) {
		timestamp = System.currentTimeMillis();
	    }
	    Date timeAt = new Date(timestamp);
	    int count = deliverMapper.getDeliverRecordListCount(StringUtils.join(shopIds, ","),
		    status, timeAt);
	    List<DeliverRecord> list = deliverMapper.getDeliverRecordList(
		    StringUtils.join(shopIds, ","), status, pageSize, timeAt);
	    List<Long> orderIds = new ArrayList<Long>();
	    for (DeliverRecord d : list) {

		orderIds.add(d.getOrderId());

		DeliverRecordOrder entity = new DeliverRecordOrder();
		BeanUtils.copyProperties(d, entity);
		result.add(entity);
	    }
	    if (!orderIds.isEmpty()) {
		List<Order> orders = orderService.getOrderByIds(orderIds);
		for (DeliverRecordOrder d : result) {
		    for (Order o : orders) {
			if (d.getOrderId().equals(o.getId())) {
			    d.setDaySn(o.getDaySn());
			    d.setPhone(o.getPhone());
			    d.setConsigness(o.getConsigness());
			    d.setTotalPrice(o.getTotalPrice());
			    d.setDeliverPoi(o.getDeliverPoi());
			    d.setType(o.getType());
			    d.setDist(o.getDist());
			    d.setDeliverFee(BigDecimal.valueOf(d.getDeliverFee())
				    .add(BigDecimal.valueOf(d.getCurrentTip())).doubleValue());
			    if (d.getStatusChangeAt() == null) {
				d.setStatusChangeAt(d.getDeliverAt());
			    }
			    long time = d.getStatusChangeAt().getTime() / 1000;
			    long t = System.currentTimeMillis() / 1000;
			    if (d.getStatus().equals(DeliverRecordStatus.waiting.getVal())) {
				time = d.getDeliverAt().getTime() / 1000;
			    } else if (d.getStatus().equals(DeliverRecordStatus.abnormal.getVal())) {
				time = d.getDeliverAt().getTime() / 1000;
			    } else if (d.getStatus().equals(DeliverRecordStatus.completed.getVal())) {
				time = d.getDeliverAt().getTime() / 1000;
				t = d.getStatusChangeAt().getTime() / 1000;
			    }
			    long pending = (t - time) / 60 > 0 ? (t - time) / 60 : 1;
			    d.setPendMinute((int) pending);
			    break;
			}
		    }
		}
	    }
	    return new Resp(Consts.Code.SUCCESS, null, result, count);
	}

	return new Resp(Consts.Code.SUCCESS, null, result, 0);
    }

    @Transactional(rollbackFor = Throwable.class, propagation = Propagation.REQUIRED)
    public int addTips(Long id, Double tips) throws Exception {
	int res = deliverMapper.addTips(id, tips);
	if (res > 0) {
	    DeliverRecordOrder record = deliverMapper.getDeliverRecordOrder(id);
	    dataService.addTips(record.getId(), record.getCurrentTip());
	}
	return res;
    }

    @Transactional(rollbackFor = Throwable.class, propagation = Propagation.REQUIRED)
    public int cancel(Long id, Integer canel_reasonId) throws Exception {
	deliverMapper.deleteTask(String.valueOf(id));
	DeliverRecordOrder record = deliverMapper.getDeliverRecordOrder(id);
	int res = deliverMapper.cancelRecord(id);
	if (res > 0 && record.getStatus() != 0) {
	    boolean b = dataService.cancel(id, canel_reasonId);
	    if (!b) {
		throw new Exception("cancel error");
	    }
	}
	return res;
    }

    public DeliverRecordOrder getNeedCancelDeliverRecordByOrderId(Long orderId) {
	return deliverMapper.getNeedCancelDeliverRecordByOrderId(orderId);
    }

    public List<Long> getHasDeliverRecordByOrderIds(List<Long> orderIds) {
	if (orderIds.isEmpty()) {
	    return Collections.emptyList();
	}
	return deliverMapper.getHasDeliverRecordByOrderIds(StringUtils.join(orderIds, ","));
    }

    public List<DadaReasons> getReasonsList(Long id) {
	return dataService.getReasonsList(id);
    }

    public int addAccount(DeliverAccount entity) {
	return deliverMapper.addDeliverAccount(entity);
    }

    public int addWifiAccount(WifiAccount entity) {
	boolean f = feiEService.addprinter(entity.getSn(), entity.getSecret());
	if (f) {
	    return deliverMapper.addWifiAccount(entity);
	}
	return 0;
    }

    public List<DeliverAccount> getDeliverAccountList(Long userId) {
	return deliverMapper.getDeliverAccountList(userId);
    }

    public DeliverAccount getDeliverAccountByType(Long auserId, Integer deliverType) {
	return deliverMapper.getDeliverAccountByType(auserId, deliverType);
    }

    public int deleteTaskByStopAuto(String type, String shopId) {
	return deliverMapper.deleteTaskByStopAuto(type, shopId);
    }

    public int getWaitingTask(Long auserId) {
	return deliverMapper.getWaitingTask(auserId);
    }

    public List<WifiAccount> getWifiAccountList(Long auserId) {
	return deliverMapper.getWifiAccountList(auserId);
    }

    public WifiAccount getUseWifiAccount(Long auserId) {
	List<WifiAccount> list = this.getWifiAccountList(auserId);
	// 目前只有飞蛾打印机，默认就是使用它
	if (list.isEmpty()) {
	    return null;
	} else {
	    return list.get(0);
	}

    }
}
